package com.zhenyi.youqu.core;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.zhenyi.core.sms.SMSHandler;

import cn.hutool.json.JSONUtil;

public class ZHSMSUtils extends SMSHandler {

	private final String AK = "LTAIWlxtPKEUCnIK";
	private final String SK = "4nS6cCCrjWvmiCwlwNNHdXG1Ym3fEc";
	private final String SIGN_NAME = "植绘";
	private final String TEMPLATE_CODE = "SMS_161275122";

	@Override
	protected Ret onSend(String mobile, String code) {
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AK, SK);
		IAcsClient client = new DefaultAcsClient(profile);

		CommonRequest request = new CommonRequest();
		// request.setProtocol(ProtocolType.HTTPS);
		request.setMethod(MethodType.POST);
		request.setDomain("dysmsapi.aliyuncs.com");
		request.setVersion("2017-05-25");
		request.setAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", mobile);
		request.putQueryParameter("SignName", SIGN_NAME);
		request.putQueryParameter("TemplateCode", TEMPLATE_CODE);
		request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
		// request.putQueryParameter("OutId", "OutId");
		try {
			CommonResponse response = client.getCommonResponse(request);
			String msg = JSONUtil.parseObj(response.getData()).getStr("Message");
			if ("OK".equals(msg)) {
				return Ret.ok("msg", msg);
			}
			if (PropKit.getBoolean("devMode", false)) {
				System.out.println(response.getData());
				return Ret.fail("msg", msg);
			}
			return Ret.fail();
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return Ret.fail();
	}

	@Override
	protected String getProjectKey() {
		return "YouQu";
	}

	public static void main(String[] args) {
		ZHSMSUtils yqsmsUtils = new ZHSMSUtils();
		yqsmsUtils.sendSMS("13631290232");
	}

}
